<template>
  <el-row class="data-lists">
    <el-col :span="9" :class="{ shake: disabled }"
      ><div class="data-item-one flx-row">
        <div class="item-left">
          <img src="../../assets/home.png" alt="" srcset="" />
        </div>
        <div class="item-right">
          <div class="item-right-top">
            <div class="tit">主账号信息--【{{ msaterInfo.name }}】</div>
            <div class="num" style="font-size: medium;">{{ msaterInfo.available ? msaterInfo.available : 0 }}-{{msaterInfo.currency?msaterInfo.currency:''}}-{{ msaterInfo.in_dual_mode ? '双仓': '单仓' }}</div>
          </div>
          <div class="line"></div>
          <div class="item-right-bottom flx-row">
            <div class="item">
              <div class="tit">持仓盈亏</div>
              <div class="num" style="font-size: medium;">{{ msaterInfo.unrealised_pnl ? msaterInfo.unrealised_pnl : '' }}</div>
            </div>
            <div class="item">
              <div class="tit">净盈亏</div>
              <div class="num" style="font-size: medium;">{{ msaterInfo.history.pnl ? msaterInfo.history.pnl : 0 }}</div>
            </div>
            <div class="item">
              <div class="tit">资金费用</div>
              <div class="num" style="font-size: medium;">{{ msaterInfo.history.fund ? msaterInfo.history.fund : 0 }}</div>
            </div>
          </div>
        </div>
      </div></el-col
    >
    <el-col :span="15" :class="{ shakeRight: disabled }">

      <!-- 数据看板模块 -->
      <dashboards :tradeInfo="tradeInfo" :msaterInfo="msaterInfo" :uptemplate="uptemplate"></dashboards>
    </el-col>
  </el-row>
  <el-row class="dataLayer">
    <!-- 交易记录 -->
    <el-col :span=" 24 ">
      <div class="table">
        <div class="tit">账号管理</div>
        <!-- 交易表格显示 -->
        <div class="table-box">
          <div class="opraet">

            <div class="item-btn">
              <el-badge>  
                <el-button size="large" type="danger" @click="allSettingsign">全部设置【单仓】</el-button>
              </el-badge>
            </div>
            <div class="item-btn">
              <el-badge>  
                <el-button size="large" type="success" @click="allSettingdouble">全部设置【双仓】</el-button>
              </el-badge>
            </div>
            <div class="item-btn">
              <el-badge>  
                <el-button size="large" @click="allCloseOrderOperationMoreFn">全部平仓</el-button>
              </el-badge>
            </div>
            <div class="item-btn">
              <el-badge>  
                <el-button size="large" type="warning" @click="CaptainOperation ">队长操作</el-button>
              </el-badge>
            </div>
            <div class="item-btn">
              <el-dropdown>
                <el-button type="primary" size="large">
                  {{ listtemp?listtemp:'点我选择操作编队' }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="activelisttemp(1)">第一编队</el-dropdown-item>
                    <el-dropdown-item @click="activelisttemp(2)">第二编队</el-dropdown-item>
                    <el-dropdown-item @click="activelisttemp(3)">第三编队</el-dropdown-item>
                    <el-dropdown-item @click="activelisttemp(4)">第四编队【测试队】</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          <el-divider />
          <!-- <div v-for="(item, index) in allacountList">
            <div class="item card" :key="index" v-if="item.name == mastername.user.UserInfo.name" >
              <tradCard :acountInfo="item" :mark_price="tradeInfo[0]?tradeInfo[0].mark_price:0" :key="item.id" ref="myComponentRef" />
            </div>
          </div> -->
          <div v-for="(item, index) in allacountList">
            <div class="item card" :key="index" v-if="item.contingent==='1'" :class="{active: item.name == mastername.user.UserInfo.name}" >
              <div class="symbol">{{ item.contingent }}</div>
              <tradCard :acountInfo="item" :CaptainParams="CaptainParams" :mark_price="tradeInfo[0]?tradeInfo[0].mark_price:0" :key="item.id" ref="myComponentRef" />
            </div>
          </div>
          <div v-for="(item, index) in allacountList">
            <div class="item card" :key="index" v-if="item.contingent==='2'" :class="{active: item.name == mastername.user.UserInfo.name}" >
              <div class="symbol second">{{ item.contingent }}</div>
              <tradCard :acountInfo="item" :CaptainParams="CaptainParams" :mark_price="tradeInfo[0]?tradeInfo[0].mark_price:0" :key="item.id" ref="myComponentRef" />
            </div>
          </div>
          <div v-for="(item, index) in allacountList">
            <div class="item card" :key="index" v-if="item.contingent==='3'" :class="{active: item.name == mastername.user.UserInfo.name}" >
              <div class="symbol third">{{ item.contingent }}</div>
              <tradCard :acountInfo="item" :CaptainParams="CaptainParams" :mark_price="tradeInfo[0]?tradeInfo[0].mark_price:0" :key="item.id" ref="myComponentRef" />
            </div>
          </div>
          <div v-for="(item, index) in allacountList">
            <div class="item card" :key="index" v-if="item.contingent==='4'" :class="{active: item.name == mastername.user.UserInfo.name}" >
              <div class="symbol third">{{ item.contingent }}</div>
              <tradCard :acountInfo="item" :CaptainParams="CaptainParams" :mark_price="tradeInfo[0]?tradeInfo[0].mark_price:0" :key="item.id" ref="myComponentRef" />
            </div>
          </div>
          <!-- <test/> -->
          <!-- 表格样式的账号列队 -->
          <!-- <div class="cardTable">
              <accountTabel />
          </div> -->

        </div>
      </div>
    </el-col>    
  </el-row>
  <!-- 复制操作抽屉 -->
  <drawerComponent ref="drawerComponentRef" 
  :drawer="drawer" 
  :acountInfo="allacountList[0]" 
  :mark_price="tradeInfo[0]?tradeInfo[0].mark_price:0" 
  @sendParams="handleReceivedParams"
  @openPosition="allCreateOrderOperationMoreFn"
  @openPosition1 ="allCreateOrderOperationLoseFn"
  @openPosition2 ="allCreateOrderOperationMorelimitFn"
  @openPosition3 ="allCreateOrderOperationLoselimitFn"
  @closePosition="allCloseOrderOperationMoreFn"
  @closePosition1="allCloseOrderOperationDuoFn"
  @closePosition2="allCloseOrderOperationKongFn"
  @handleDeleteFn="allhandleDeleteFn"
  />

</template>

<script setup>
import { onMounted,onUnmounted ,ref ,provide} from 'vue'
import tradCard from '@/views/home/components/tradCard.vue'
import { getFuturesAccountBalances,getAllFuturesTickers,getAllTradeRecords,getTeamAccount } from '@api/apis.js'
import { getAllAccount ,getFuturesInfosigle} from '@api/apis.js'
import { ElMessage } from 'element-plus'
import dashboards from '@/views/home/components/dashboards.vue'
import { useWebSocket } from '@/views/home/plugin/useWebSocket'
import drawerComponent from '@/views/home/components/drawerComponent.vue'
import accountTabel from '@/components/TableList/accountTabel.vue'
import { useTradeStore } from "@/store/tradeStore"
import { captainOprate } from "@/store/captainOprate"

const store = useTradeStore()
const positions = store.positions

const store1 = captainOprate()

let listtemp = ref('')


// 测试组件
import test from './components/test.vue'

const notList = ref([])
const disabled = ref(false)

const mastername = ref(JSON.parse(localStorage.getItem('user')))

// 队长操作函数
let drawer = ref(false)
let drawerComponentRef = ref(null)
function CaptainOperation(){
  if(drawerComponentRef){
    drawerComponentRef.value.toggleDrawer()
  }
}

let CaptainParams = ref({})

function handleReceivedParams(params) {
  CaptainParams.value = params
}

// 获取主账户信息

const msaterInfo = ref({
    "total": "0",
    "unrealised_pnl": "0",
    "position_margin": "0",
    "order_margin": "0",
    "available": "0",
    "point": "0",
    "currency": "USDT",
    "in_dual_mode": false,
    "enable_credit": false,
    "position_initial_margin": "0",
    "maintenance_margin": "0",
    "bonus": "0",
    "history": {
        "dnw": "0",
        "pnl": "0",
        "fee": "0",
        "refr": "0",
        "fund": "0",
        "point_dnw": "0",
        "point_fee": "0",
        "point_refr": "0",
        "bonus_dnw": "0",
        "bonus_offset": "0"
    }
})
function getAccountBalances(){
    const {gate_key,gate_secret,name} = allacountList.value[0]

    getFuturesAccountBalances({
        gate_key,
        gate_secret,
        settle:'usdt',
        contract:'',
    }).then(res=>{
        if (res.data.code==200) {
            msaterInfo.value = res.data.data
            msaterInfo.value.name = name

        } else {
        ElMessage.error(`请求失败，错误代码：${res.data.code}，错误信息：${res.data.msg}`);
        }
    }).catch(error => {
        ElMessage.error('请求发生错误，请检查网络或稍后再试');
        console.error('获取账户列表时出现错误:', error);
    });
}



// 获取交易信息 需要没两秒请求一次 需要配置相中设置请求频率
const tradeInfo = ref(
    {
        "contract": "BTC_USDT",
        "last": "62893.1",
        "change_percentage": "2.46",
        "total_size": "125327097",
        "low_24h": "60671.3",
        "high_24h": "63253.5",
        "volume_24h": "151547329",
        "volume_24h_btc": null,
        "volume_24h_usd": null,
        "volume_24h_base": "15154",
        "volume_24h_quote": "953128131",
        "volume_24h_settle": "953128131",
        "mark_price": "62893.1",
        "funding_rate": "0.000059",
        "funding_rate_indicative": "0.000059",
        "index_price": "62920.94",
        "quanto_base_rate": null,
        "basis_rate": null,
        "basis_value": null,
        "lowest_ask": "62883.1",
        "highest_bid": "62883"
    }
)
const uptemplate = ref(true)



// 获取所有账户信息
const allacountList = ref([
  {
      "id": 1,
      "name": "master_first",
      "gate_key": "a0fd8db874ffd1b494809ac7545048d7",
      "gate_secret": "f01fdeac32a756cee33bf109de577b9b5aa7b938164e3d8c29c76b54792e3390",
      "contingent": "1"
  }
])

function activelisttemp(params){
  if (params===1) {
    listtemp.value ='第一编队'
  }else if(params===2){
    listtemp.value = '第二编队'
  }else if (params===3) {
    listtemp.value = '第三编队'
  }
  getTeamAccount({
    contingent:params
  }).then((res) => {
    if (res.data.code=200) {
      allacountList.value = res.data?.data;
    }else{
      ElMessage.error(`请求失败，错误代码：${response.code}，错误信息：${response.msg}`);
    }
  });
}


function getAllAccountInfo(params){
  getTeamAccount({
    contingent:params
  })
  .then((res) => {
    const response = res.data;
    if (response.code === 200) {
      allacountList.value = response.data;
      ElMessage({
        message: response.msg,
        type: 'success',
      });
    } else {
      ElMessage.error(`请求失败，错误代码：${response.code}，错误信息：${response.msg}`);
    }
  })
  .catch((error) => {
    ElMessage.error('请求发生错误，请检查网络或稍后再试');
    console.error('获取账户列表时出现错误:', error);
  });
}

// 全部开仓
const myComponentRef = ref(null);


const callAllComponents = (methodName,arg) => {
  myComponentRef.value.forEach((componentInstance) => {
    componentInstance[methodName](arg);
  });
};

const allCreateOrderOperationMoreFn = (done) => {
  callAllComponents('allcreatOrderOperationMore')
  done();
};

const allCreateOrderOperationLoseFn = (done) => {
  callAllComponents('allcreatOrderOperationLose')
  done();
};

const allCreateOrderOperationMorelimitFn = (done) => {
  callAllComponents('allcreatOrderOperationMorelimit')
  done();
};

const allCreateOrderOperationLoselimitFn = (done) => {
  callAllComponents('allcreatOrderOperationLoselimit')
  done();
};

const allCloseOrderOperationMoreFn =(done)=>{
  callAllComponents('allCloseOrderOperationLose')
  done();
}

const allCloseOrderOperationDuoFn =(done)=>{
  callAllComponents('allCloseOrderOperationDuo')
  done();
}
const allCloseOrderOperationKongFn =(done)=>{
  callAllComponents('allCloseOrderOperationKong')
  done();
}

const allhandleDeleteFn =(index,done)=>{
  callAllComponents('allhandleDelete',index)
  done();
}

const allSettingsign = ()=>{
  callAllComponents('allSettingsign')
}
const allSettingdouble = ()=>{
  callAllComponents('allSettingdouble')
}

// 定时活动

const timerId1 = ref(null)
const timerId2 = ref(null)

// 初始化WebSocket连接
// const baseUrl = 'http://localhost:8100/'
const baseUrl = 'http://120.77.214.128:8100/';
const { tradeInfo: tradeInfoSocket, userPositions, queryUserPositions, disconnectSocket } = useWebSocket(baseUrl);


// 使用 provide 函数来提供数据
provide('tradeInfo', tradeInfoSocket);
provide('userPositions',userPositions)


onMounted(() => {
  disabled.value = true
  getAllAccountInfo(1)
  // timerId1.value = setInterval(getTradeInfo,1000*1)
  timerId2.value = setInterval(getAccountBalances,1000*1)
  // timerId2.value = setInterval(getAccountBalances,1000*100)
})


onUnmounted(() => {
    // 组件销毁时清理定时器
    if (timerId1.value || timerId1.value) {
        clearInterval(timerId1.value);
        clearInterval(timerId2.value);
        timerId1.value = null;
        timerId2.value = null;
        console.log('Timer has been cleared.');
    }
});
</script>

<style lang="scss" scoped>
@import './index.scss';
.blockcheinInfo{
  min-width: 1120px;
  background-color: white;
  border-radius: 6px;
  height: 165px;
  padding-top: 10px;
  .item{
    width: 100%;
    height: 45%;
    position: relative;
    .left-box{
      float: left;
      width: 140px;
      height: 100%;
      line-height: 40px;
      text-align: center;
      border-right: 1px solid rgba(138, 198, 249, 0.539);
      .tit{
        font-size: 18px;
        font-weight: 600;
      }
      .sub{
        font-size: 14px;
        color: rgb(134, 164, 190);
        line-height: 30px;
      }
    }
    .last{
      float: left;
      width: 150px;
      height: 100%;
      font-size: 20px;
      text-align: center;
      line-height: 70px;
      font-weight: 600;
      font-family:Arial, Helvetica, sans-serif;
    }
    .trandInfo{
      width: 65%;
      height: 100%;
      float: left;
      .item{
        width: 100px;
        float: left;
        text-align: center;
        color: rgb(117, 117, 118);
        .tit{
          font-size: 14px;
          line-height: 30px;
        }
        .num{
          font-size: 15px;
          font-weight: 600;
          line-height: 30px;
        }
      }
    }

  }
}

.table{
  background-color: rgb(255, 255, 255);
  margin-top: 15px;
  border-radius: 8px;
  padding: 10px;
  .tit{
    margin-left: 10px;
    width: 100%;
    font-size: 20px;
    font-weight: 600;
  }
  .table-box{
    height: 70vh;
    overflow-y: scroll;
    .opraet{
      width: 90%;
      height: 20px;
      padding: 10px;
      .item-btn{
        float: left;
        margin-right: 20px;
      }
    }
    .contingent{
      margin-left: 15px;
      font-size: 20px;
      font-weight: 600;
    }
    .item{
      float: left;
      width: 340px;
      height: 350px;
      background-color: #ffffff;
      border: 1px solid rgba(138, 198, 249, 0.539);
      box-shadow:  0px 0px 10px #BFF6C3;
      border-radius: 6px;
      margin: 10px;
      padding: 10px;
      position: relative;
    }
    .card{
      .symbol{
        position: absolute;
        right: 0px;
        top: 0px;
        width: 40px;
        height: 30px;
        overflow: hidden;
        line-height: 30px;
        background-color: #ff5e00af;
        text-align: center;
        color: white;
        border-radius-top-right: 50%;
      }
      .second{
        background-color: #ff4d4d;
      }
      .third{
        background-color: #7d5fff;
      }
      position: relative;
      overflow-y: scroll;
      transition: all  0.3s, transform 0.6s;
    }
    .card:hover{
      width: 25%;
      height: 650px;
      position: relative;
    }
    .active{
      border: 2px solid #874CCC;
    }
    .card::-webkit-scrollbar {
        display: none;
    }

  }

}

.cardTable{
  width: 100%;
  transform: translateX(0);
}
</style>
<!-- http://120.77.214.128:8888/aa36ebe1 -->